import 'package:intl/intl.dart';

extension IntExt on int {
  ///格式化时间戳
  String toTime(pattern) {
    var date = DateTime.fromMillisecondsSinceEpoch(this);
    return DateFormat(pattern).format(date);
  }

  ///判断该时间戳是否是今日
  bool get isToday {
    final now = DateTime.now();
    final date = DateTime.fromMillisecondsSinceEpoch(this);
    return date.year == now.year && date.month == now.month && date.day == now.day;
  }

  ///判断该时间戳是否是今日
  bool get isYesterday {
    final now = DateTime.now();
    final yesterday = now.subtract(const Duration(days: 1));
    final date = DateTime.fromMillisecondsSinceEpoch(this);
    return date.year == yesterday.year && date.month == yesterday.month && date.day == yesterday.day;
  }

  ///获取友好型星期，今天、明天、后天，周一..(其他就显示周几)
  String toFriendlyWeek() {
    final now = DateTime.now();
    final msgDate = DateTime.fromMillisecondsSinceEpoch(this);
    // 今天
    if (msgDate.year == now.year && msgDate.month == now.month && msgDate.day == now.day) {
      return "今天";
    }
    // 明天
    final tomorrow = now.add(const Duration(days: 1));
    if (msgDate.year == tomorrow.year && msgDate.month == tomorrow.month && msgDate.day == tomorrow.day) {
      return "明天";
    }
    // 后天
    final afterTomorrow = now.add(const Duration(days: 2));
    if (msgDate.year == afterTomorrow.year && msgDate.month == afterTomorrow.month && msgDate.day == afterTomorrow.day) {
      return "后天";
    }
    // 星期几（Dart: 1=周一 … 7=周日）
    switch (msgDate.weekday) {
      case DateTime.monday:
        return "周一";
      case DateTime.tuesday:
        return "周二";
      case DateTime.wednesday:
        return "周三";
      case DateTime.thursday:
        return "周四";
      case DateTime.friday:
        return "周五";
      case DateTime.saturday:
        return "周六";
      case DateTime.sunday:
        return "周日";
      default:
        return "周日";
    }
  }

  //格式化单位
  String toFormatSize() {
    final kb = this / 1024.0;
    if (kb < 1) {
      return "${this}B";
    }
    final nf = NumberFormat("#.##");
    final mb = kb / 1024.0;
    if (mb < 1) {
      return "${nf.format(kb)}KB";
    }
    final gb = mb / 1024.0;
    if (gb < 1) {
      return "${nf.format(mb)}MB";
    }
    final tb = gb / 1024.0;
    if (tb < 1) {
      return "${nf.format(gb)}GB";
    }
    return "${nf.format(tb)}TB";
  }

  ///单位为秒的，转换成友好型的时间段
  String toFriendlyDuration() {
    if (this < 60) {
      return "$this秒";
    }
    if (this < 3600) {
      return "${this ~/ 60}分钟"; // ~/ 表示整除
    }
    final hours = this ~/ 3600;
    final minutes = (this - hours * 3600) ~/ 60;
    if (minutes > 0) {
      return "$hours小时$minutes分钟";
    } else {
      return "$hours小时";
    }
  }
}
